from flask_jwt_extended import (
    create_access_token,
    create_refresh_token,
    jwt_required,
    get_jwt_identity
)
from flask import jsonify, request
from flask_jwt_extended import create_refresh_token, get_jwt_identity
from ..models import User, db
from app.auth.login import *
def walkpace():
    data = request.get_json()
    walkpace = data.get(walkpace)
    if data is None or not isinstance(data, dict) or not data:
        return jsonify(
            code=201, 
            msg=f"缺少参数",
            data=None
        ), 200
    # 验证Ticket有效性
    device = data.get('deviceId')
    if not get_device(device):
        return jsonify(code=202,
                       msg="未知设备ID",
                       data=None
                       
                       ), 200

    # 签名验证
    if not verify_signature(data['token'], data['deviceId'], get_password(data['deviceId']), data['signature']):
        return jsonify(
            code=203,
            msg="无效签名",
            data=None
                       ), 200

    walkpace = int(walkpace)  # 类型转换
    recommendation = 8000  # 默认推荐值
        
    if walkpace < 5000:
            recommendation = 8000
            message = f"您今天走了{walkpace}步，建议尝试增加到{recommendation}步，开启健康生活！(ง •_•)ง"
    elif 5000 <= walkpace < 8000:
            recommendation = 10000
            message = f"{walkpace}步的成绩不错！再挑战{recommendation}步达成每日目标吧！✨"
    elif 8000 <= walkpace < 10000:
            recommendation = 10000
            message = f"已经{walkpace}步啦！距离黄金标准{recommendation}步只差{recommendation-walkpace}步，加油！🚶♂️"
    else:
            recommendation = min(walkpace + 2000, 15000)  # 上限保护
            message = f"🏆 您已超额完成{walkpace}步！" + (
                f"挑战{recommendation}步吧！" if recommendation > walkpace 
                else "建议保持当前运动量，注意休息~"
            )

    
    return jsonify(
            code=200,
            message=message,
            data={
                "current": walkpace,
                "recommendation": recommendation
            }
        ), 200
    
    
def  sleep_recommendation():
    data = request.get_json()
    sleeptime = data.get('sleeptime')
    if data is None or not isinstance(data, dict) or not data:
        return jsonify(
            code=201, 
            msg=f"缺少参数",
            data=None
        ), 200
    # 验证Ticket有效性
    device = data.get('deviceId')
    if not get_device(device):
        return jsonify(code=202,
                       msg="未知设备ID",
                       data=None
                       
                       ), 200

    # 签名验证
    if not verify_signature(data['token'], data['deviceId'], get_password(data['deviceId']), data['signature']):
        return jsonify(
            code=203,
            msg="无效签名",
            data=None
                       ), 200
    sleep_hours = float(sleeptime)
    normal_range = "成年人推荐睡眠时长:6-9小时/日"
    health_tips = [
            "保持固定作息时间",
            "睡前避免使用电子设备",
            "营造黑暗安静的睡眠环境"
        ]

    if sleep_hours < 4:
            recommendation = "⚠️ 严重睡眠不足，建议立即调整作息并咨询医生"
    elif 4 <= sleep_hours < 6:
            recommendation = "睡眠时间较短，建议增加午休并保持规律作息"
    elif 6 <= sleep_hours <= 9:
            recommendation = "睡眠时长在健康范围内，继续保持良好作息"
    else:
            recommendation = "注意:过度睡眠可能影响健康,建议不超过9小时"

    return jsonify(
            code=200,
            message="睡眠数据分析成功",
            data={
                "recommendation": recommendation,
                "normal_range": normal_range,
                "your_sleeptime": f"{sleep_hours:.1f} 小时",
                "health_tips": health_tips
            }
        ), 200
    
    
def  wearingtime():
    data = request.get_json()
    walkpace = data.get(walkpace)
    if data is None or not isinstance(data, dict) or not data:
        return jsonify(
            code=201, 
            msg=f"缺少参数",
            data=None
        ), 200
    # 验证Ticket有效性
    device = data.get('deviceId')
    if not get_device(device):
        return jsonify(code=202,
                       msg="未知设备ID",
                       data=None
                       
                       ), 200

    # 签名验证
    if not verify_signature(data['token'], data['deviceId'], get_password(data['deviceId']), data['signature']):
        return jsonify(
            code=203,
            msg="无效签名",
            data=None
                       ), 200
    return jsonify(
        code=200,
        message={"time":time

        }
    ), 200
    
    
def breath():  
    data = request.get_json()
    breath = data.get(breath)
    if data is None or not isinstance(data, dict) or not data:
        return jsonify(
            code=201, 
            msg=f"缺少参数",
            data=None
        ), 200
    # 验证Ticket有效性
    device = data.get('deviceId')
    if not get_device(device):
        return jsonify(code=202,
                       msg="未知设备ID",
                       data=None
                       
                       ), 200

    # 签名验证
    if not verify_signature(data['token'], data['deviceId'], get_password(data['deviceId']), data['signature']):
        return jsonify(
            code=203,
            msg="无效签名",
            data=None
                       ), 200
    breath = int(breath)  # 类型转换
    normal_range = "成人静息正常值:12-20次/分钟"
        
    if breath < 12:
            recommendation = "检测到呼吸过缓(<12次/分钟)，建议咨询医生"
    elif 12 <= breath <= 20:
            recommendation = "呼吸频率正常(12-20次/分钟)，保持良好的呼吸习惯"
    else:
            recommendation = "检测到呼吸过速(>20次/分钟)，建议缓慢深呼吸放松"

    return jsonify(
            code=200,
            message="呼吸数据解析成功",
            data={
                "recommendation": recommendation,
                "normal_range": normal_range,
                "your_breath": breath
            }
        ), 200
    
    
def getdata():
    data = request.get_json()
    
    # 检查数据有效性
    if data is None or not isinstance(data, dict) or not data:
        return jsonify(
            code=201,
            msg="请求参数不能为空",
            data=None
        ), 200
    
    # 检查必要字段
    required_fields = ['deviceId', 'token', 'signature', 'data']
    for field in required_fields:
        if field not in data:
            return jsonify(
                code=201,
                msg=f"缺少必要参数: {field}",
                data=None
            ), 200
    
    device_id = data['deviceId']
    
    # 验证设备有效性
    if not get_device(device_id):
        return jsonify(
            code=202,
            msg="未知设备ID",
            data=None
        ), 200
    
    # 验证签名
    if not verify_signature(
        data['token'],
        device_id,
        get_password(device_id),
        data['signature']
    ):
        return jsonify(
            code=203,
            msg="数字签名验证失败",
            data=None
        ), 200
    
    # 处理健康数据
    health_data = data['data']
    
    # 构建响应数据（使用冒号且处理可选字段）
    response_data = {
        'high': health_data.get('high'),
        'low': health_data.get('low'),
        'heartbeat': health_data.get('heartbeat'),
        'breathe': health_data.get('breathe'),
        'walkpace': health_data.get('walkpace'),
        'consume': health_data.get('consume'),
        'sleeptime': health_data.get('sleeptime')
    }
    
    # 检查必要健康数据字段
    if response_data['high'] is None or response_data['low'] is None:
        return jsonify(
            code=204,
            msg="缺少必要健康数据参数",
            data=None
        ), 200
    
    return jsonify(
        code=200,
        msg="健康数据获取成功",
        data=response_data
    ), 200
    
    

          